package com.study.spmongodb.book.wwj.sp;

import java.util.Optional;
import java.util.Random;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ExecutionException;

/**
 * @author MI
 * @version 1.0
 * @date 2020/11/24 22:57
 */
public class CompletableFutureAction1 {
    private final static Random RANDOM = new Random(System.currentTimeMillis());

    public static void main(String[] args) throws ExecutionException, InterruptedException {

        final CompletableFuture<Double> completableFuture = new CompletableFuture<>();
        new Thread(() -> {
            final double v = get();
            completableFuture.complete(v);
        }, "").start();
        System.out.println("===no====block");
        // Optional.ofNullable(completableFuture.get()).ifPresent(System.out::println);
        completableFuture.whenComplete((v, t) -> {
            Optional.ofNullable(v).ifPresent(System.out::println);
            Optional.ofNullable(t).ifPresent(x -> x.printStackTrace());
        });
    }

    static double get() {
        final int i = RANDOM.nextInt(10000);
        try {
            Thread.sleep(i);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        return RANDOM.nextDouble();
    }
}
